package com.kl.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.kl.domain.LogisticsStoreDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.Result;
import com.kl.entity.LogisticsStore;
import com.kl.entity.StaffWarehouse;
import com.kl.feign.LineServcieFeign;
import com.kl.service.ILogisticsStoreService;
import com.kl.service.IStaffWarehouseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import jdk.nashorn.internal.runtime.linker.LinkerCallSite;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@RestController
@RequestMapping("/logistics-store")
@Api(value = "车辆管理功能接口")
@RefreshScope //nacos配置中心 开启自动刷新配置
public class LogisticsStoreController {

    @Resource
    private ILogisticsStoreService iLogisticsStoreService;
    @Resource
    private IStaffWarehouseService iStaffWarehouseService;
    @Resource
    private LineServcieFeign lineServcieFeign;


    @ApiOperation("根据ID进行查询")
    @GetMapping("selectLogisticsStoreById/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "站点ID",required = true, paramType = "path")
    })
    public Result<LogisticsStoreDTO> selectLogisticsStoreById(@PathVariable Long id){
        LogisticsStore byId = iLogisticsStoreService.getById(id);
        LogisticsStoreDTO logisticsStoreDTO = new LogisticsStoreDTO();
        if (logisticsStoreDTO == null){
            return Result.build(ConstantEnum.ERROR).setResult("没有这个站点");
        }
        BeanUtils.copyProperties(byId , logisticsStoreDTO);
        return Result.build(ConstantEnum.SUCCESS).setResult(logisticsStoreDTO);
    }

    //候补    查询所有
    @GetMapping("selectLogisticsStoreAll")
    public Result<LogisticsStoreDTO> selectLogisticsStoreAll(){

        List<LogisticsStoreDTO> list = null;
        try {
            List<LogisticsStore> logisticsStores = iLogisticsStoreService.selectLogisticsStoreAll();
            String string = JSONObject.toJSONString(logisticsStores);
            list = JSONArray.parseArray(string, LogisticsStoreDTO.class);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(list);
    }

    @ApiOperation("站点增加")
    @PostMapping("saveLogisticsStore")
    @ApiImplicitParams({
            @ApiImplicitParam(name="logisticsStoreDTO",value = "站点的实体类",required = true, paramType = "body")
    })
    public Result saveLogisticsStore(@RequestBody LogisticsStoreDTO logisticsStoreDTO){
        LogisticsStore logisticsStore = new LogisticsStore();
        BeanUtils.copyProperties(logisticsStoreDTO,logisticsStore);
        boolean save = iLogisticsStoreService.save(logisticsStore);
        if (save){
            List<LogisticsStore> list1 = iLogisticsStoreService.list();
            String s = JSONObject.toJSONString(list1);
            List<LogisticsStoreDTO> list = JSONObject.parseArray(s,LogisticsStoreDTO.class);
            String storeAddr = logisticsStoreDTO.getStoreAddr();

            Result result = lineServcieFeign.selectCount(storeAddr,list);
            if (result.getCode().equals(1007)){
                return Result.build(ConstantEnum.FaillBack).setResult("增加线路熔断,成功与否未知,或许是超时了,请查看数据是否有误");
            }
            return Result.build(ConstantEnum.SUCCESS);
        }
        return Result.build(ConstantEnum.ERROR);
    }

    @ApiOperation("站点修改")
    @PutMapping("updateLogisticsStore/{id}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="logisticsStoreDTO",value = "站点的实体类",required = true, paramType = "body"),
            @ApiImplicitParam(name="id",value = "实体类的ID",required = true, paramType = "path")
    })
    public Result updateLogisticsStore(@PathVariable Long id, @RequestBody LogisticsStoreDTO logisticsStoreDTO){
        LogisticsStore logisticsStore = new LogisticsStore();
        BeanUtils.copyProperties(logisticsStoreDTO,logisticsStore);
        logisticsStore.setId(id);
        boolean b = logisticsStore.updateById();
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation("站点删除(逻辑删除)")
    @DeleteMapping("deleteLogisticsStore")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "实体类的ID(或数组)",required = true, paramType = "body")
    })
    public Result deleteLogisticsStore(@RequestBody Long[] id ){
        List<Long> ids = new ArrayList<>();
        for (Long aLong : id) {
            ids.add(aLong);
        }
        boolean b = iLogisticsStoreService.removeByIds(ids);
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation("站点模糊查询分页")
    @GetMapping("selectLogisticsStoreLikePage")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNumber",value = "起始页数",required = false, paramType = "query"),
            @ApiImplicitParam(name="pageSize",value = "每页条数",required = false, paramType = "query"),
            @ApiImplicitParam(name="storeAddr",value = "网点地址",required = false, paramType = "query"),
            @ApiImplicitParam(name="storeName",value = "网点名称",required = false, paramType = "query"),
            @ApiImplicitParam(name="business",value = "网点业务(发货 快递派送 快递自提)",required = false, paramType = "query"),
            @ApiImplicitParam(name="ifWarehouse",value = "是否是物流仓库",required = false, paramType = "query"),
    })
    public Result<Map<String,Object>> selectLogisticsStoreLikePage(@RequestParam(defaultValue = "1")Integer pageNumber,
                                                                   @RequestParam(defaultValue = "3")Integer pageSize,
                                                                   @RequestParam(required = false)String storeAddr,
                                                                   @RequestParam(required = false)String storeName,
                                                                   @RequestParam(required = false)String business,
                                                                   @RequestParam(required = false)Integer ifWarehouse){


        Map<String, Object> map = iLogisticsStoreService.selectLogisticsStoreLikePage(pageNumber, pageSize, storeAddr, storeName, business, ifWarehouse);

        return Result.build(ConstantEnum.SUCCESS).setResult(map);
    }

    @ApiOperation("站点模糊查询")
    @GetMapping("selectByCityName")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cityName",value = "城市名称",required = true, paramType = "query")
    })
    public Result<List<LogisticsStoreDTO>> selectByCityName(@RequestParam("cityName") String cityName){
        List<LogisticsStoreDTO> list = null;
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.like("store_addr",cityName);
            list = iLogisticsStoreService.list(wrapper);
        }catch (Exception e){
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(list);
    }

    @ApiOperation("站点授权(开通/关闭授权)")
    @PutMapping("updateLogisticsStoreBySiteRole/{SiteRole}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value = "实体类的ID(或数组)",required = true, paramType = "body"),
            @ApiImplicitParam(name="SiteRole",value = "授权与否的标识",required = true, paramType = "path")
    })
    public Result updateLogisticsStoreBySiteRole(@RequestBody Long[] id,@PathVariable Integer SiteRole){
        if (SiteRole == 1){
            for (Long aLong : id) {
                LogisticsStore logisticsStore = new LogisticsStore();
                logisticsStore.setId(aLong);
                logisticsStore.setSiteRole(1);
                boolean b = logisticsStore.updateById();
            }
        }
        if (SiteRole == 2){
            for (Long aLong : id) {
                LogisticsStore logisticsStore = new LogisticsStore();
                logisticsStore.setId(aLong);
                logisticsStore.setSiteRole(2);
                boolean b = logisticsStore.updateById();
            }
        }
        return Result.build(ConstantEnum.SUCCESS);
    }

    @ApiOperation("站点城市id查询接口")
    @PutMapping("/selectByCityId")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cityId",value = "城市id",required = true, paramType = "query")
    })
    public Result<List<LogisticsStoreDTO>> selectByCityId(@RequestParam("cityId")String cityId){
        List<LogisticsStoreDTO> list = null;
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("city_id",cityId);
            List<LogisticsStore> list1 = iLogisticsStoreService.list(queryWrapper);
            String string = JSONObject.toJSONString(list1);
            list = JSONObject.parseArray(string, LogisticsStoreDTO.class);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(list);
    }

}
